package com.xunmall.base.validation.validator;

import com.xunmall.base.util.StringUtils;
import com.xunmall.base.validation.annotation.IsPhoneNumber;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: WangYanjing
 * @Date: 2018/12/27 10:53
 * @Description:
 */
public class IsPhoneNumberValidator implements ConstraintValidator<IsPhoneNumber, String> {

    private Map<String, String[]> patterns;

    private String type;

    private String locale;

    @Override
    public void initialize(IsPhoneNumber constraintAnnotation) {
        this.patterns = new HashMap<String, String[]>();
        this.patterns.put("zh_CN", new String[]{"^(0[0-9]{2,3}\\-)?([2-9][0-9]{6,7})+(\\-[0-9]{1,4})?$", "^(0|86|17951)?(13[0-9]|14[0-9]|15[0-9]|17[0-9]|18[0-9]|19[0-9])[0-9]{8}$", "^[48]00[0-9]{7}$"});
        this.type = constraintAnnotation.type();
        this.locale = constraintAnnotation.locale();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (StringUtils.isEmpty(value)) {
            return true;
        }
        if (!patterns.containsKey(locale)) {
            return true;
        }
        if (StringUtils.equals(this.type, "line")) {
            return StringUtils.match(value, patterns.get(locale)[0]);
        }
        if (StringUtils.equals(this.type, "mobile")) {
            return StringUtils.match(value, patterns.get(locale)[1]);
        }
        if (StringUtils.equals(this.type, "enterprice")) {
            return StringUtils.match(value, patterns.get(locale)[0]) || StringUtils.match(value, patterns.get(locale)[1]) || StringUtils.match(value, patterns.get(locale)[2]);
        }
        return StringUtils.match(value, patterns.get(locale)[0]) || StringUtils.match(value, patterns.get(locale)[1]);
    }

}
